
console.info("load preload.js")
console.info(window.location.href);

window.electron = require('electron');
var stockCfg = require('../config/stock.json');
var dayjs = require("dayjs")


var getCurDay = function(){
    var curDate = new Date();
    var diffday = 0;
    
    if(curDate.getHours()<9 || (curDate.getHours()==9 && curDate.getMinutes()<23)){
        diffday = 1;
        var week = curDate.getDay();
        if(week==0) diffday =2;
        else if(week==1) diffday =3;
    }
    var $curday = dayjs().subtract(diffday,"day").format("YYYYMMDD");
    return $curday;
}

window.onload=function(){
    if(window.$){
        console.info("have jquery")
        $(document).ajaxSuccess(function(event,xhr,options){
            options.url;
            var data=xhr.responseText;
            data = JSON.parse(data);
            if(!data || data.Status!=0) return;
            if(options.url.indexOf("Search/GetFundsFlow")!=-1){
                pageMgr.dealTradeHis(data);
            }else if(options.url.indexOf("Com/queryAssetAndPositionV1")!=-1){
                pageMgr.dealMoneyInfo(data);
            }else if(options.url.indexOf("Search/GetDealData")!=-1){
                pageMgr.dealTodayInfo(data);
            }else if(options.url.indexOf("Transfer/GetTotalTranList")!=-1){
                pageMgr.dealBankInfo(data);
            }else if(options.url.indexOf("Finance/TTB/GetTtbHistoryProfit")!=-1){
                pageMgr.dealJJInfo(data);
            }

            
        });
        if(window.alertMsg){
            // alertMsg("", "预加载成功", "info");
            console.log("预加载成功");
        }
        pageMgr.initPage();
    }else{
        console.info("no jquery")
    }
}
var pageMgr = {
    initPage:function(){
        console.info("initPage")
        var url = location.href;
        if(url.indexOf("jy.xzsec.com/Login")!=-1){
            this.initLoginPage()
        }else if(url.indexOf("jy.xzsec.com/Trade/Buy")!=-1){
            this.initBuyPage()
        }else if(url.indexOf("jy.xzsec.com/Trade/Sale")!=-1){
            this.initSalePage()
        }else if(url.indexOf("/capital/ranking")!=-1){
            // https://www.kaipanla.com/index.php/capital/ranking
            this.initKplPage()
        }
        
    },
    initKplPage(){
        getKPLList();
        setInterval(function(){
            getKPLList();
        },1*2000)
    },
    initBuyPage(){
        if($("[data-control=delegateWay]").find("li[data-value=0a]").length==0) return;
        $("[data-control=delegateWay]").find("li[data-value=0a]").click();
        // $("#boxmrsl .add").click();
        // $("#boxmrsl .add").click();
        // $("#iptCount").val(300);
        setTimeout(()=>{
            // $("#btnConfirm").click()
            setTimeout(()=>{
                // $(".btn-default-blue").click()
                // $(".btn-default-gray").click()
                // setTimeout(()=>{
                //     window.close();
                // },5000);
            },300);
        },300);
    },
    initSalePage(){
        if($("[data-control=delegateWay]").find("li[data-value=0f]").length==0) return;
        $("[data-control=delegateWay]").find("li[data-value=0f]").click();
        // $("#boxmrsl .add").click();
        // $("#boxmrsl .add").click();
        // $("#iptCount").val(300);
        setTimeout(()=>{
            // $("#btnConfirm").click()
            setTimeout(()=>{
                // $(".btn-default-blue").click()
                // $(".btn-default-gray").click()
                // setTimeout(()=>{
                //     window.close();
                // },5000);
            },300);
        },300);
        
    },
    initLoginPage(){
        var userEl = document.getElementById("txtZjzh");
        if(!userEl) return;
        if(userEl) userEl.value = stockCfg.account || "540640134143";
        document.getElementById("rdsc45").checked=true;
    },
    dealTradeHis(data){
        if(data.Data.length==0)return;
        var opername = "insertHis";
        this.registerListen(opername);

        data.Data.map((item,idx)=>{
            if(item.Ywsm.indexOf("红股")!=-1){
                if(!item.Cjbh) item.Cjbh = "red-"+item.Fsrq+item.Zqdm;
            }
            if(item.Ywsm.indexOf("新股入帐")!=-1){
                if(!item.Cjbh) item.Cjbh = "new-"+item.Fsrq+item.Zqdm;
                item.Cjjg = item.Wtjg;
                item.Fsje = -(item.Wtsl*item.Wtjg);
            }
            if(!item.Cjsl || !item.Gddm || item.Cjbh.length<5) return;
            if(item.Ywsm.indexOf("红利")!=-1) return;
            var param = {type:"insertHis",name:opername,
                objInfo:{
                    tradeno:item.Cjbh,
                    month:item.Fsrq.substring(0,6),
                    day:item.Fsrq,
                    time:item.Fssj,
                    code:item.Zqdm,
                    name:item.Zqmc,
                    isBuy:item.Fsje<=0?1:0,
                    type:item.Ywsm,
                    amount:item.Fsje<=0?item.Cjsl:-item.Cjsl,
                    leftNum: item.Gpye,
                    price:item.Cjjg,
                    money:item.Fsje,
                    fee1:item.Jsxf,
                    fee2:item.Sxf>item.Jsxf?item.Sxf-item.Jsxf:0,
                    fee3:item.Yhs,
                    fee4:item.Yjghf,
                    leftmoney:item.Zjye,
                    account:item.Gddm,
                    market:item.Market
                }};
            electron.ipcRenderer.send("doSql",param)
        });
    },
    dealMoneyInfo(data){
        if(data.Data.length==0)return;
        var accountInfo = data.Data[0];
        var storeList = accountInfo.positions;

        var zxsz = 0; //计算最新市值,避免每日理财产品影响
        storeList.map(item=>{
            zxsz+= item.Zxsz*1;
        })
        zxsz = zxsz.toFixed(0)*1;
        
        this.insertMoneyInfo(accountInfo,zxsz);
        this.insertStoreInfo(storeList);
    },
    registerListen(opername){
        if(!window["lisiten-"+opername]){
            window["lisiten-"+opername] = true;
            electron.ipcRenderer.on(opername+'Res', (event, res) => {
                try{
                    console.info(opername+'Res dbdata:',res);
                }catch(ex){
                    alertMsg("查询异常:"+ex.message)
                }
            })
        }
    },
    insertMoneyInfo(data,zxsz){
        var opername = "insertMoneyInfo";
        this.registerListen(opername);
        data.Zxsz = zxsz || data.Zxsz;
        var param = {type:opername,name:opername,
            objInfo:{
                day:getCurDay(),
                zzc:data.Zzc,
                zsz:data.Zxsz,
                kyzj:data.Kyzj,
                ccyk:data.Ljyk,
                createtime:new Date(),
            }};
        electron.ipcRenderer.send("doSql",param)
    },
    insertStoreInfo(list){
        var opername = "insertStore";
        this.registerListen(opername);
        var param = {type:opername,name:opername, objInfo:[]};
        list.map((item)=>{
            param.objInfo.push(
                {
                    day:getCurDay(),
                    code:item.Zqdm,
                    name:item.Zqmc,
                    amount:item.Zqsl,
                    cbj:item.Cbjg,
                    curprice:item.Zxjg,
                    zxsz:item.Zxsz,
                    fdyk:item.Ljyk,
                    rate:(item.Ykbl*100).toFixed(3),
                    createtime:new Date(),
                }
            );
        });
        
        electron.ipcRenderer.send("doSql",param)
    },
    dealTodayInfo(data){
        if(data.Data.length==0)return;
        var opername = "insertToday";
        this.registerListen(opername);
        var list = data.Data;
        var param = {type:opername,name:opername, objInfo: []};
        list.map((item)=>{
            param.objInfo.push(
                {
                    cjbh:item.Cjbh,
                    cjsj:item.Cjsj,
                    code:item.Zqdm,
                    name:item.Zqmc,
                    mmlb:item.Mmlb,
                    mmsm:item.Mmsm,
                    cjsl:item.Mmlb=="B"?item.Cjsl:-item.Cjsl,
                    cjjg:item.Cjjg,
                    cjje:item.Mmlb=="B"?-item.Cjje:item.Cjje,
                    createtime:new Date(),
                }
            );
        });
        
        electron.ipcRenderer.send("doSql",param)
    },
    dealBankInfo(data){
        if(data.Data.length==0)return;
        var opername = "insertBank";
        this.registerListen(opername);
        var list = data.Data;
        list.map((item)=>{
            var param = {type:opername,name:opername, objInfo: {}};
            param.objInfo=(
                {
                    tradeno:item.Zzrq+item.Zzsj,
                    day:item.Zzrq,
                    time:item.Zzsj,
                    name:item.Yhmc,
                    oper:item.Ywmc,
                    status:item.Status,
                    money:item.Zzje,
                    remark:item.Qrxx,
                    createtime:new Date(),

                }
            );
            electron.ipcRenderer.send("doSql",param)
        });
        
    },
    dealJJInfo(data){
        if(data.Data.length==0)return;
        var opername = "insertJJ";
        this.registerListen(opername);
        var list = data.Data[0].SyDetail;
        list.map((item)=>{
            var param = {type:opername,name:opername, objInfo: {}};
            param.objInfo=(
                {
                    tradeno:item.Syrq+"_002183",
                    day:item.Syrq,
                    code:"002183",
                    name:"广发天天红",
                    money:item.Sy,
                    createtime:new Date(),

                }
            );
            electron.ipcRenderer.send("doSql",param)
        });
    }
}


function getKPLList(){
    var trs = $("#listbox_zxg .li_table_b>tbody>tr")
    var list = [];
    for(var i=0;i<trs.length;i++){
        var row = trs[i];
        var item ={
            "c":$(row).find(".td2 .c").text(),
            "n":$(row).find(".td2 .n").text(),
            "p":$(row).find(".td4").text(),
            "r":$(row).find(".td3").text().replace("%",""),
            "watch":true,
            "jjzb":0
        }
        item.totalTrade = $(row).find(".td-box .td6").text()
        item.clearTrade = $(row).find(".td-box .td7").text()
        item.jjzb = tranUnit(item.clearTrade)*100/tranUnit(item.totalTrade)*1;
        item.jjzb = item.jjzb.toFixed(2)*1
        list.push(item);
    }
    if(window.electron) electron.ipcRenderer.send("updateKPLList",list)
    return list;
}

function tranUnit(money){
    if(money.indexOf("万")!=-1){
        return Number(money.replace("万",""))*10000;
    }else if(money.indexOf("亿")!=-1){
        return Number(money.replace("亿",""))*100000000;
    }
    return Number(money);
}